/// 通用API响应模型 - Base API Response Model
///
/// 定义后端API返回的通用数据结构
/// Defines the common data structure returned by backend API
///
/// 所有API响应都包含code、message、data三个字段
/// All API responses contain code, message, and data fields
class BaseResponse<T> {
  /// 响应状态码 - Response status code
  final String? code;

  /// 响应消息 - Response message
  final String? message;

  /// 响应数据 - Response data
  final T? data;

  const BaseResponse({
    this.code,
    this.message,
    this.data,
  });

  /// 从JSON创建响应对象 - Create response object from JSON
  factory BaseResponse.fromJson(
    Map<String, dynamic> json,
    T Function(dynamic) fromJsonT,
  ) {
    return BaseResponse<T>(
      code: json["code"]?.toString(),
      message: json["message"]?.toString(),
      data: json["data"] != null ? fromJsonT(json["data"]) : null,
    );
  }

  /// 转换为JSON - Convert to JSON
  Map<String, dynamic> toJson(Object? Function(T?) toJsonT) {
    return {
      "code": code,
      "message": message,
      "data": toJsonT(data),
    };
  }

  /// 判断请求是否成功 - Check if request is successful
  bool get isSuccess => code == "200" || code == "0";

  /// 判断请求是否失败 - Check if request failed
  bool get isFailure => !isSuccess;
}

/// 列表响应模型 - List Response Model
/// 用于处理返回数组数据的API响应
/// Used to handle API responses that return array data
class ListResponse<T> extends BaseResponse<List<T>> {
  const ListResponse({
    String? code,
    String? message,
    List<T>? data,
  }) : super(code: code, message: message, data: data);

  /// 从JSON创建列表响应对象 - Create list response object from JSON
  factory ListResponse.fromJson(
    Map<String, dynamic> json,
    T Function(Map<String, dynamic>) fromJsonT,
  ) {
    List<T>? dataList;
    if (json["data"] != null && json["data"] is List) {
      dataList = List<T>.from(
          json["data"].map((x) => fromJsonT(x as Map<String, dynamic>)));
    }

    return ListResponse<T>(
      code: json["code"]?.toString(),
      message: json["message"]?.toString(),
      data: dataList,
    );
  }

  // 列表响应的 JSON 转换可直接使用父类提供的 toJson，
  // 调用方需传入将 List<T>? 转换为期望结构的函数。
}
